package com.example.demo.service.ipml;

import com.example.demo.common.pageResult;
import com.example.demo.comtan.ComTan;
import com.example.demo.entiy.Employee;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.service.Employeeservice;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;
import java.util.List;

import com.github.pagehelper.Page;

@Service
public class EmployeeService implements Employeeservice {
    @Autowired
    EmployeeMapper employeeMapper;
    @Override
    public Employee getUser(Long id) {
        return employeeMapper.getUser(id);
    }


    @Override
    public Employee login(String userName, String possWord) {
        String passWrod = DigestUtils.md5DigestAsHex(possWord.getBytes());
        Employee user = employeeMapper.getByUserName(userName);
        if (user ==null){
            String  msg = "登录失败";
            throw new IllegalArgumentException(msg);
        }
        if (!user.getPassword().equals(passWrod)){
            throw new IllegalArgumentException("密码错误");
        }
        if (user.getStatus() == 0){
            throw new IllegalArgumentException("账号已禁用");
        }
        return user;
    }

    @Override
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return "退出成功！";
    }

    @Override
    public int charageStatus(Employee employee, Long empId) {
        return employeeMapper.charageStatus(employee,empId);
    }

    @Override
    public pageResult<Employee> pageInfo(int page, int pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        Page<Employee> page1 = employeeMapper.pageInfo(page,pageSize,name);
        long total = page1.getTotal();
        List<Employee> result = page1.getResult();
        return pageResult.result(total, result);
    }

    @Override
    public void save(HttpServletRequest request, Employee employee) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employee,emp);

        emp.setStatus(ComTan.STUSTAS_INFO_jH);

        emp.setCreateTime(LocalDateTime.now());

        emp.setUpdateTime(LocalDateTime.now());

        Long empid =(Long) request.getSession().getAttribute("employee");
        emp.setCreateUser(empid);
        emp.setUpdateUser(empid);
        emp.setPassword(DigestUtils.md5DigestAsHex(ComTan.PASS_WORD.getBytes()));
        employeeMapper.save(emp);
    }

    @Override
    public boolean getUsername(String username) {
        Employee userName = employeeMapper.getByUserName(username);
        return userName == null;
    }
}
